package com.hhl.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhl.flower.common.constant.CouponConstant;
import com.hhl.flower.mapper.CouponMapper;
import com.hhl.flower.pojo.entity.Coupon;
import com.hhl.flower.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author Liubuzhu
 * @description 针对表【coupon】的数据库操作Service实现
 * @createDate 2024-06-23 21:34:25
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon>
		implements CouponService {
	@Autowired
	private CouponMapper couponMapper;

	public List<Coupon> getListByUser(Integer userId) {
		QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("u_id", userId);
		return couponMapper.selectList(queryWrapper);
	}

	public List<Coupon> getListByStatus(Integer userId, Integer status) {
		QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("u_id", userId);
		if (Objects.equals(status, CouponConstant.NOT_USED)) {
			queryWrapper.eq("status", CouponConstant.NOT_USED)
					.ge("end_time", LocalDateTime.now());
		} else if (Objects.equals(status, CouponConstant.USED)) {
			queryWrapper.eq("status", CouponConstant.USED);
		} else if (Objects.equals(status, CouponConstant.EXPIRED)) {
			queryWrapper.eq("status", CouponConstant.EXPIRED)
					.lt("end_time", LocalDateTime.now());
		}
		return couponMapper.selectList(queryWrapper);
	}

	public Integer getCouponCount(Integer userId) {
		QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("status", CouponConstant.NOT_USED)
				.ge("end_time", LocalDateTime.now());
		return Math.toIntExact(couponMapper.selectCount(queryWrapper));
	}

	public void addCoupon(Integer userId, Double discount, Double threshold, Integer termTime) {
		Coupon coupon = new Coupon();
		coupon.setDiscount(discount);
		coupon.setName("优惠券");
		coupon.setStatus(CouponConstant.NOT_USED);
		coupon.setCreateTime(LocalDateTime.now());
		coupon.setTermTime(termTime);
		coupon.setThreshold(threshold);
		coupon.setUId(userId);
		coupon.setEndTime(LocalDateTime.now().plusSeconds(termTime));
		couponMapper.insert(coupon);
	}

}




